"""
homework04 - 设计获得样本数据描述性统计信息的函数

集中趋势：均值、中位数、众数
离散趋势：极差、方差、标准差

Author: Administrator
Date: 2024/1/22
"""
import math
import random


def ptp(data):
    """求极差（全距）"""
    return max(data) - min(data)


def average(data):
    """求均值"""
    return sum(data) / len(data)


def variance(data):
    """求方差"""
    x_bar = average(data)
    # total = 0
    # for num in data:
    #     total += (num - x_bar) ** 2
    # return total / (len(data) - 1)
    temp = [(num - x_bar) ** 2 for num in data]
    return sum(temp) / (len(temp) - 1)


def standard_deviation(data):
    """求标准差"""
    # return math.sqrt(variance(data))
    return variance(data) ** 0.5


def median(data):
    """找中位数"""
    temp, size = sorted(data), len(data)
    if size % 2 != 0:
        return temp[size // 2]
    else:
        # return (temp[size // 2 - 1]) + temp[size // 2] / 2
        return average(temp[size // 2 - 1: size // 2 + 1])


# __name__是一个隐藏变量，它代表了当前模块（文件）的名字
# 如果直接通过Python解释器运行homework04.py这个文件，__name__的值是__main__
# 如果是在其他的模块（文件）中导入了homework04，那么此时__name__的值就是homework04
if __name__ == '__main__main':
    nums = [random.randrange(1, 100) for _ in range(8)]
    print(nums)
    print(ptp(nums))
    print(average(nums))
    print(variance(nums))
    print(standard_deviation(nums))
    print(median(nums))